package com.fc.config.shiro.filter;



import com.fc.common.util.SpringContextUtils;
import com.fc.entity.SysUser;
import com.fc.service.SysPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.HashSet;
import java.util.Set;


public class URLPathMatchingFilter extends PathMatchingFilter {
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        if(sysPermissionService == null)
            sysPermissionService = SpringContextUtils.getApplicationContext().getBean(SysPermissionService.class);

        if(sysPermissionService == null){
            System.out.println("permissionService为空");
        }
        String requestURI = getPathWithinApplication(request);
        System.out.println("requestURI:" + requestURI);

        Subject subject = SecurityUtils.getSubject();
        // 如果没有登录，就跳转到登录页面
        if (!subject.isAuthenticated()) {
            WebUtils.issueRedirect(request, response, "/login.html");
            return false;
        }

        // 看看这个路径权限里有没有维护，如果没有维护，一律放行(也可以改为一律不放行)
        System.out.println("permissionService:"+ sysPermissionService);
        boolean needInterceptor = sysPermissionService.getPermisisonByURL(requestURI);
        if (!needInterceptor) {
            System.out.println("走的是权限尚未维护的这条路");
            return true;
        } else {
            //那就目前暂定 用户端就不设置 角色和权限了
            System.out.println("走的是权限已在数据库中维护的这条路");
            boolean hasPermission = false;
            SysUser sysUser = (SysUser) subject.getPrincipal();
            Set<String> permissionUrls = new HashSet<String>(sysPermissionService.getPermissionUrlsByUsername(sysUser.getUsername()));
            for (String url : permissionUrls) {
                // 这就表示当前用户有这个权限
                if (url.equals(requestURI)) {
                    hasPermission = true;
                    System.out.println("当前url是"+url);
                    break;
                }
            }

            if (hasPermission)
                return true;
            else {
                UnauthorizedException ex = new UnauthorizedException("当前用户没有访问路径 " + requestURI + " 的权限");
                subject.getSession().setAttribute("ex", ex);
                WebUtils.issueRedirect(request, response, "/unauthorized");
                return false;
            }

        }

    }

}
